package game.engine.base

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView

class RenderView @JvmOverloads constructor(
        ctx: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0
) : SurfaceView(ctx, attrs, defStyle), SurfaceHolder.Callback, Runnable {

    // 实际宽高
     var realWidth = 0f
     var realHeight = 0f
     var isReady = false
    private var running = false

    init {
        holder.addCallback(this)
        isFocusable = true
        isFocusableInTouchMode = true
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        running = true
        Director.instance.firstFrame = true
        Thread(this).start()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        resize(width, height)
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        running = false
    }

    private fun resize(width: Int, height: Int) {
        realWidth = width.toFloat()
        realHeight = height.toFloat()
        if (!isReady) {
            if (CoreDebug.DirectorDebug){
                CoreDebug.info("renderView is Ready")
            }
            isReady = true
        }
    }

    override fun run() {
        while (running) {
            if (!holder.surface.isValid) {
                continue
            }

            // 开启硬件加速的 canvas
            val canvas = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                holder.lockHardwareCanvas()
            } else {
                holder.lockCanvas()
            }
            if (canvas != null) {
                Director.instance.mainLoop(canvas)
                holder.unlockCanvasAndPost(canvas)
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {

        val director = Director.instance

        if (!isReady || !director.inited) {
            return super.onTouchEvent(event)
        }

        // 将 x,y 转换成游戏坐标
        val scale = director.windowAdapter.scale
        val dx = event.x - realWidth / 2f
        val dy = event.y - realHeight / 2f
        director.addTouch(Touch(event.action, dx / scale, dy / scale))
        return true
    }
}